var express = require('express')  //这是一个什么鬼的框架
var app = express()
const fs = require('fs')
const path = require('path')
const http = require('http')
const qs = require('querystring')
const axios = require('axios')

// 解决跨域问题
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'GET,POST,DELETE,OPTIONS')
    res.header('X-Powered-By', '3.2.1')
    // res.header('Content-Type', 'application/json;charset=utf-8')
    next()
})
//静态文件
app.use('/img', express.static('img'));
var access_token = ''

var imgArr = []
//读取图片文件列表
fs.readdir(path.join(__dirname, `img`), (err, files) => {
    if (err) {
        console.log(err)
    } else {
        imgArr = files
    }
})
//图片列表接口
app.get('/userInfo', (req, res) => {
    res.status(200);
    res.json(imgArr) //给客户端响应的数据
    // console.log(req.query)
})

var data = {
    grant_type: 'client_credentials',
    client_id: 'VlzQfg8ZgUIc5YQgxDnAcQnI',
    client_secret: 'nHHjKxDHT4iIDO9Rpv3DXbNP0LlxbvM8'
}
var post_data = qs.stringify(data)
var options = {
    hostname: 'aip.baidubce.com',
    path: '/oauth/2.0/token?' + post_data,
    agent: false,
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
};
//发送请求，获取人脸识别的Access Token https://aip.baidubce.com/oauth/2.0/token
http.get(options, function (res) {
    // 在标准输出中查看运行结果
    // var data = res.pipe(process.stdout); //这个鬼东西不知道怎么拿值，只能通过写入文件再拿
    //将获取的数据写入文件
    res.pipe(fs.createWriteStream('./baidu-token.json'));
    //读取文件
    fs.readFileSync('./baidu-token.json', 'utf8', (err, readFile) => {
        console.log(111)
        if (err) {
            console.log('读取失败' + err)
        } else {
            let data = readFile
            let jsonAccessToken = JSON.parse(data)
            access_token = jsonAccessToken
            console.log(access_token, '555')
            //创建接口把access_token返回给客户端
            app.get('/accessToken', (req, res) => {
                res.status(200);
                res.json(global.access_token) //给客户端响应的数据
            })
        }
    })
});

//人脸检测  受不了了用插件吧
axios.post('https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token=' + global.access_token, {
    image: 'http://127.0.0.1/img/u=2659562911,580809381&fm=253&app=138&f=JPEG&fmt=auto&q=75.jpg',
    image_type: 'URL'
}).then(res => {
    // res.pipe(process.stdout)
    // console.dir(res)
})

//配置服务端口
var server = app.listen(80, function () {

    var host = server.address().address
    var port = server.address().port

    console.log("应用实例，访问地址为 http://%s:%s", host, port)
})